import json
import time
import subprocess

from config.config import container_monitor_flag
from crawler.utils.func_tools import get_env
from crawler.connection import redis_conn
from crawler.monitor.dingding_group_robot import DingDingGroupRobot

__all__ = ['ContainerMonitor']


class ContainerMonitor(object):
    """容器监控服务"""

    def __init__(self, spider_name_list):
        self.hostname = ''
        self.env = get_env()
        self.spider_name_list = spider_name_list

    def get_hostname(self):
        if not self.hostname:
            for i in range(10):
                a, self.hostname = subprocess.getstatusoutput('hostname')
                if self.hostname:
                    break
                time.sleep(1)

    def run_monitor(self):
        if container_monitor_flag:
            self.get_hostname()
            for spider_name in self.spider_name_list:
                try:
                    monitor_key = spider_name + '_' + 'victor'
                    self.monitor(monitor_key + '|' + self.hostname)
                except Exception as error_message:
                    current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                    message_format = '\n' \
                                     '>内核名称：%(spider_name)s</font>\n' \
                                     '>问题描述：<font color=\"comment\">爬虫容器运行异常(监控程序报错)</font>\n' \
                                     '>报错信息：<font color=\"comment\">%(error_message)s</font>\n' \
                                     '>发生时间：<font color=\"comment\">%(current_time)s</font>'
                    message = message_format % {
                        'spider_name': spider_name,
                        'error_message': error_message,
                        'current_time': current_time,
                    }
                    from crawler.logger import other_logger
                    other_logger.info('Container Monitor Error : {}'.format(message))
                    self.send_warning_message(message)

    def monitor(self, monitor_key):
        last_info = json.loads(redis_conn.hget('crawler_container_monitor', monitor_key))
        last_idle_time = int(last_info['logTime'])
        now_time = int(time.time())
        if now_time - last_idle_time > 3600:
            current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            message_format = '<font color=\"warning\">容器监控预警</font>\n\n' \
                             '>内核名称：<font color=\"comment\">%(service)s</font>\n\n' \
                             '>问题描述：<font color=\"comment\">容器进程疑似Block，无法接受调度任务</font>\n\n' \
                             '>发生时间：<font color=\"comment\">%(current_time)s</font>'
            message = message_format % {
                'service': last_info['service'],
                'current_time': current_time,
            }
            self.send_warning_message(message)
        from crawler.logger import other_logger
        other_logger.info('Container Monitor Running : {}'.format(json.dumps(last_info)))

    @staticmethod
    def send_warning_message(message):
        dd = DingDingGroupRobot()
        dd.send_data(message)


if __name__ == "__main__":
    pass
    # container_monitor = ContainerMonitor([])
    # container_monitor.run_monitor()
